import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

//课程类（单行）
class Course {
  String courseName; //课程名
  String time; //课程时间
  String location; //位置

  //构造
  Course(
      {required this.courseName, required this.time, required this.location});
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: SchedulePage(),
    );
  }
}

//课表主体
class SchedulePage extends StatefulWidget {
  const SchedulePage({super.key});
  @override
  _SchedulePageState createState() => _SchedulePageState();
}

class _SchedulePageState extends State<SchedulePage> {
  //课表内容（默认有2行，调试展示用）
  List<Course> courses = [
    Course(courseName: '数学', time: '8:00-9:30', location: '教室A'),
    Course(courseName: '英语', time: '9:45-11:15', location: '教室B'),
  ];

  @override //课表的主体
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('课表'),
      ),
      //pading可以设置内边距
      body: Padding(
        padding: const EdgeInsets.all(0.0), //在文本周围增加20像素的内边距。
        //这个组件可以防止溢出
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: DataTable(
            //初始行（每列的字段）
            columns: const [
              DataColumn(label: Text('课程名称')),
              DataColumn(label: Text('时间')),
              DataColumn(label: Text('地点')),
              DataColumn(label: Text('编辑')),
            ],
            //正文行
            rows: _buildCourseRows(),
          ),
        ),
      ),
      //点击触发添加新行（右下角按钮）
      floatingActionButton: FloatingActionButton(
        onPressed: _addCourse,
        tooltip: '添加课程',
        child: const Icon(Icons.add),
      ),
    );
  }

  //bulid并填充默认课程表
  List<DataRow> _buildCourseRows() {
    List<DataRow> rows = [];
    for (int i = 0; i < courses.length; i++) {
      rows.add(
          //每行的结构
          DataRow(
        cells: [
          DataCell(Text(courses[i].courseName)),
          DataCell(Text(courses[i].time)),
          DataCell(Text(courses[i].location)),
          //点击事件：编辑课程（弹出编辑框）
          DataCell(IconButton(
            icon: const Icon(Icons.edit),
            onPressed: () {
              _editCourse(i);
            },
          )),
        ],
      ));
    }
    return rows;
  }

  //对已有的行编辑
  void _editCourse(int index) async {
    //编辑对话框界面（await等待新课程编辑完毕）
    Course? newCourse = await showDialog<Course>(
      context: context,
      builder: (BuildContext context) {
        return EditCourseDialog(course: courses[index]);
      },
    );

    //若不为空创建新行成功 -》添加到courses中保存
    if (newCourse != null) {
      setState(() {
        courses[index] = newCourse;
      });
    }
  }

  //添加新行
  void _addCourse() {
    //初始化内容
    Course newCourse = Course(courseName: '新课程', time: '时间', location: '地点');
    setState(() {
      courses.add(newCourse);
    });
  }
}

//课程编辑对话框
class EditCourseDialog extends StatefulWidget {
  final Course course;
  const EditCourseDialog({super.key, required this.course});

  @override
  _EditCourseDialogState createState() => _EditCourseDialogState();
}

class _EditCourseDialogState extends State<EditCourseDialog> {
  //TextEditingController这个可以接收用户输入的内容
  late TextEditingController courseNameController; //课程名字
  late TextEditingController timeController; //时间
  late TextEditingController locationController; //地点

  @override
  void initState() {
    super.initState();
    courseNameController = TextEditingController(text: widget.course.courseName);
    timeController = TextEditingController(text: widget.course.time);
    locationController = TextEditingController(text: widget.course.location);
  }

  @override
  Widget build(BuildContext context) {
    //编辑对话框主体
    return AlertDialog(
      title: const Text('编辑课程'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          TextField(
            controller: courseNameController,
            decoration: const InputDecoration(labelText: '课程名称'),
          ),
          TextField(
            controller: timeController,
            decoration: const InputDecoration(labelText: '时间'),
          ),
          TextField(
            controller: locationController,
            decoration: const InputDecoration(labelText: '地点'),
          ),
        ],
      ),
      actions: <Widget>[
        //取消：直接回到上一级页面
        TextButton(
          child: const Text('取消'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        //保存：将新Course返回给上一级页面
        TextButton(
          child: const Text('保存'),
          onPressed: () {
            Course newCourse = Course(
              courseName: courseNameController.text,
              time: timeController.text,
              location: locationController.text,
            );
            Navigator.of(context).pop(newCourse);
          },
        ),
      ],
    );
  }
}
